package api

import (
	"github.com/gin-gonic/gin"
	"guard/internal/app/user/models"
	"guard/internal/conf"
	"guard/internal/errors"
	"guard/internal/middleware"
	"guard/internal/result"
	"guard/internal/tool"
	"net/http"
)

// 用户信息首页
func indexUser(c *gin.Context) {

	usernameKey := c.GetString(conf.Conf.Cache.LoginUserKey)

	c.HTML(http.StatusOK, "index.html", gin.H{
		"username": usernameKey,
	})
}

// 注册用户
func registerUser(c *gin.Context) {

	userInfo := &models.User{}

	err := c.ShouldBindJSON(&userInfo)
	if err != nil {
		_ = c.Error(errors.OtherError("错误的请求参数"))
		return
	}

	// 1.查询用户名是否重复，用户名是否匹配正则，全部为数字，最小6位最大12位
	if !tool.VerificationParam(tool.UsernameReg, userInfo.Username) || !tool.VerificationParam(tool.PasswordReg, userInfo.Password) || len(userInfo.Nickname) > 20 {
		_ = c.Error(errors.OtherError("请求参数不符合标准"))
		return
	}

	// 1.1.判断用户密码是否符合，字母+数字，最小5位，最大18位
	// 1.2.剩下两个存进去就行
	err = userService.RegisterUser(userInfo)
	if err != nil {
		_ = c.Error(err)
		return
	}

	c.JSON(http.StatusOK, result.Build{
		Code: http.StatusOK,
		Msg:  "注册成功",
		Data: nil,
	})
}

// 修改用户信息
func modifyUserInfo(c *gin.Context) {

	var newUserInfo = struct {
		NewNickname string `json:"new_nickname,omitempty" binding:"required"`
		NewPicture  string `json:"new_picture,omitempty" binding:"required"`
	}{}
	// 绑定参数
	err := c.ShouldBindJSON(&newUserInfo)
	// 验证，ShouldBindJSON如果监测有 binding:"required"会自动验证
	if err != nil || len(newUserInfo.NewNickname) > 20 {
		_ = c.Error(errors.OtherError("参数不符合规范"))
		return
	}

	// 获取登录用户
	username := c.GetString(conf.Conf.Cache.LoginUserKey)

	// 1.直接写入数据到登录用户就行
	err = userService.ModifyUserInfo(username, newUserInfo.NewNickname, newUserInfo.NewPicture)
	if err != nil {
		_ = c.Error(err)
		return
	}

	c.JSON(http.StatusOK, result.Build{
		Code: http.StatusOK,
		Msg:  "修改成功",
		Data: nil,
	})
}

// 修改密码，验证前端传入的两个密码，验证旧密码
func modifyUserPassword(c *gin.Context) {

	var onp = struct {
		OldPassword string `json:"old_password,omitempty" binding:"required"`
		NewPassword string `json:"new_password,omitempty" binding:"required"`
	}{}

	// 验证参数
	err := c.ShouldBindJSON(&onp)
	if err != nil {
		_ = c.Error(errors.OtherError("参数不正确"))
		return
	}

	if !tool.VerificationParam(tool.PasswordReg, onp.NewPassword) {
		_ = c.Error(errors.OtherError("非法参数，或密码不符合规范"))
		return
	}

	// 获取登录用户
	username := c.GetString(conf.Conf.Cache.LoginUserKey)

	err = userService.ModifyUserPassword(username, onp.OldPassword, onp.NewPassword)
	if err != nil {
		_ = c.Error(err)
		return
	}

	// 注销当前用户
	sess := middleware.NewSessionCache(c.Writer, c.Request)
	sess.Session.Delete(conf.Conf.Cache.LoginUserKey)

	c.JSON(http.StatusOK, result.Build{
		Code: http.StatusOK,
		Msg:  "修改密码成功",
		Data: nil,
	})
}
